﻿using System;
using System.Web.Mvc;
using JSM.DataStore;

namespace JSM.MVC3.DataStore
{
	internal class ViewDataDataStoreProvider : IDataStoreProvider
	{
		private readonly ViewDataDictionary _viewDataDictionary;

		internal ViewDataDataStoreProvider(ViewDataDictionary viewDataDictionary)
		{
			_viewDataDictionary = viewDataDictionary;
		}

		void IDataStoreProvider.SetData(string key, object value)
		{
			_viewDataDictionary[key] = value;
		}

		object IDataStoreProvider.GetData(string key)
		{
			object returnValue;
			return _viewDataDictionary.TryGetValue(key, out returnValue) ? returnValue : null;
		}

		bool IDataStoreProvider.ContainsData(string key)
		{
			return _viewDataDictionary.ContainsKey(key);
		}

		internal static IDataStoreProvider GetDataStoreProvider(object controller)
		{
			if (controller == null)
				throw new ArgumentNullException("controller");
			if (controller is ControllerBase)
				return new ViewDataDataStoreProvider((controller as ControllerBase).ViewData);
			return null;
		}
	}
}
